#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <sys/wait.h>

int main()
{
	int fd[2];
	pid_t pid;	
	int nread,i;
	char buf[BUFSIZ];

	int ret = pipe(fd);	

	if(ret == -1)
	perror("pipe:");

	for(i = 0; i<2; i++)
	{
		pid = fork();
		if(pid == -1)
		perror("fork:");

		if(pid == 0)
		break;
	}	
	
	if(i == 2)
	{
		close(fd[0]);
		close(fd[1]);
		wait(NULL);
		wait(NULL);
	}
	else if(i == 0)
	{
		close(fd[1]);
		nread = read(fd[0], buf, sizeof(buf));
		write(STDOUT_FILENO, buf, nread);
		dup2(fd[0], STDIN_FILENO);
		execlp("wc", "wc", "-l", NULL);
		//close(fd[0]);
	}
	else if(i == 1)
	{
		close(fd[0]);
		write(fd[1], "hello\n", sizeof("hello\n"));
		//sleep(1); invalid sleep(1). father will be stuck in block until "wc" read data from STDIN_FILENO/fd[0].
		dup2(fd[1], STDOUT_FILENO);
		execlp("ls", "ls", NULL);
		//close(fd[1]);invalid after execlp
	}

	return 0;
}
